import React, { useState, useEffect, useMemo } from 'react';
import {
  Book,
  Shuffle,
  Trash2,
  Edit2,
  ChevronLeft,
  ChevronRight,
  RotateCcw,
  LayoutGrid,
  Check,
  X,
  Sparkles
} from 'lucide-react';
import { MistakeNotebook, MistakeQuestion } from '../../types';
import { Layout } from '../components/Layout';
import { updateMistakeNotebookName, deleteMistakeNotebook, removeQuestionFromNotebook } from '../services/storageService';

interface MistakeNotebookViewProps {
  notebook: MistakeNotebook;
  onHomeClick: () => void;
  onSettingsClick: () => void;
  sidebarContent: React.ReactNode;
  onNotebookUpdate: () => void; // To trigger refresh in parent
  onNotebookDelete: () => void; // To trigger navigation away
  onGenerateFromMistakes: (questions: MistakeQuestion[]) => void;
}

export const MistakeNotebookView: React.FC<MistakeNotebookViewProps> = ({
  notebook,
  onHomeClick,
  onSettingsClick,
  sidebarContent,
  onNotebookUpdate,
  onNotebookDelete,
  onGenerateFromMistakes
}) => {
  const [activeQuestionIndex, setActiveQuestionIndex] = useState(0);
  const [isFlipped, setIsFlipped] = useState(false);
  const [isEditingName, setIsEditingName] = useState(false);
  const [editName, setEditName] = useState(notebook.name);
  const [randomQuestions, setRandomQuestions] = useState<MistakeQuestion[]>([]);
  const [showAll, setShowAll] = useState(false);

  // Initialize random questions
  useEffect(() => {
    handleRandomize();
  }, [notebook.id, notebook.questions.length]);

  const handleRandomize = () => {
    const shuffled = [...notebook.questions].sort(() => 0.5 - Math.random());
    setRandomQuestions(shuffled.slice(0, 20));
    setActiveQuestionIndex(0);
    setIsFlipped(false);
    setShowAll(false);
  };

  const handleShowAll = () => {
    setRandomQuestions(notebook.questions);
    setActiveQuestionIndex(0);
    setIsFlipped(false);
    setShowAll(true);
  };

  const handleSaveName = () => {
    if (editName.trim() && editName !== notebook.name) {
      updateMistakeNotebookName(notebook.id, editName);
      onNotebookUpdate();
    }
    setIsEditingName(false);
  };

  const handleDeleteNotebook = () => {
    if (confirm('确定要删除这个题集吗？')) {
      deleteMistakeNotebook(notebook.id);
      onNotebookDelete();
    }
  };

  const handleRemoveQuestion = (qId: string) => {
    if (confirm('确定要移除这道题目吗？')) {
      removeQuestionFromNotebook(notebook.id, qId);
      onNotebookUpdate();
      // If it was the last question in the current view, adjust index or re-randomize
      // Simple approach: re-randomize or just let the effect handle it if length changes
      // But effect only runs on length change of *original* notebook.
      // We need to update local state too.
      const newRandoms = randomQuestions.filter(q => q.id !== qId);
      setRandomQuestions(newRandoms);
      if (activeQuestionIndex >= newRandoms.length) {
        setActiveQuestionIndex(Math.max(0, newRandoms.length - 1));
      }
    }
  };

  const currentQuestion = randomQuestions[activeQuestionIndex];

  if (!currentQuestion && notebook.questions.length > 0 && randomQuestions.length === 0) {
      // Fallback if random generation failed or empty
      return <div>Loading...</div>;
  }

  return (
    <Layout
      onSettingsClick={onSettingsClick}
      onHomeClick={onHomeClick}
      sidebarContent={sidebarContent}
    >
      <div className="flex flex-col h-full bg-slate-50/50">
        {/* Header */}
        <header className="flex items-center justify-between px-8 py-4 bg-white border-b border-slate-200">
          <div className="flex items-center gap-4">
            <div className="p-2 bg-indigo-50 text-primary rounded-lg">
              <Book className="w-5 h-5" />
            </div>
            {isEditingName ? (
              <div className="flex items-center gap-2">
                <input
                  type="text"
                  value={editName}
                  onChange={(e) => setEditName(e.target.value)}
                  className="px-2 py-1 border rounded-md text-lg font-bold text-slate-800 focus:border-primary outline-none"
                  autoFocus
                  onBlur={handleSaveName}
                  onKeyDown={(e) => e.key === 'Enter' && handleSaveName()}
                />
                <button onClick={handleSaveName} className="text-green-600 hover:text-green-700">
                  <Check size={18} />
                </button>
                <button onClick={() => setIsEditingName(false)} className="text-red-500 hover:text-red-600">
                  <X size={18} />
                </button>
              </div>
            ) : (
              <h2 className="text-xl font-bold text-slate-800 flex items-center gap-2">
                {notebook.name}
                <button
                  onClick={() => {
                    setEditName(notebook.name);
                    setIsEditingName(true);
                  }}
                  className="text-slate-400 hover:text-primary transition-colors"
                >
                  <Edit2 size={14} />
                </button>
              </h2>
            )}
            <span className="bg-slate-100 text-slate-500 px-2 py-0.5 rounded text-xs">
              共 {notebook.questions.length} 题
            </span>
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={() => onGenerateFromMistakes(notebook.questions)}
              className="flex items-center gap-2 bg-primary hover:bg-indigo-700 text-white px-3 py-1.5 rounded-lg transition-colors text-sm font-medium"
              title="根据当前题集生成强化试卷"
            >
              <Sparkles size={16} />
              生成试卷
            </button>
            <button
              onClick={handleDeleteNotebook}
              className="flex items-center gap-2 text-red-500 hover:text-red-600 hover:bg-red-50 px-3 py-1.5 rounded-lg transition-colors text-sm font-medium"
            >
              <Trash2 size={16} />
              删除题集
            </button>
          </div>
        </header>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-8">
          {notebook.questions.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full text-slate-400">
              <Book className="w-16 h-16 mb-4 opacity-20" />
              <p className="text-lg">题集为空</p>
              <p className="text-sm mt-2">在考试回顾中添加题目到这里</p>
            </div>
          ) : (
            <div className="max-w-3xl mx-auto flex flex-col h-full">
              {/* Progress Bar / Tabs */}
              <div className="flex items-center justify-center gap-1 mb-8 overflow-x-auto pb-2">
                {randomQuestions.map((_, idx) => (
                  <div
                    key={idx}
                    onClick={() => {
                      setActiveQuestionIndex(idx);
                      setIsFlipped(false);
                    }}
                    className={`h-1.5 rounded-full cursor-pointer transition-all ${
                      idx === activeQuestionIndex
                        ? 'w-10 bg-primary'
                        : 'w-10 bg-slate-200 hover:bg-slate-300'
                    }`}
                  />
                ))}
              </div>

              {/* Card */}
              {currentQuestion && (
                <div className="flex-1  relative min-h-[300px]">
                  <div
                    className={`relative w-full h-full transition-all duration-500 [transform-style:preserve-3d] cursor-pointer ${
                      isFlipped ? '[transform:rotateY(180deg)]' : ''
                    }`}
                    onClick={() => setIsFlipped(!isFlipped)}
                  >
                    {/* Front */}
                    <div className="absolute inset-0 [backface-visibility:hidden] bg-white p-8 rounded-2xl shadow-sm border border-slate-100 flex flex-col">
                      <div className="flex items-center justify-between mb-6">
                        <span className="text-xs font-bold px-2 py-1 rounded bg-slate-100 text-slate-500 uppercase tracking-wider">
                          Question {activeQuestionIndex + 1}
                        </span>
                        <span className="text-xs text-slate-400">
                          点击卡片查看答案
                        </span>
                      </div>
                      <h3 className="text-xl font-medium text-slate-800 leading-relaxed mb-8 flex-1">
                        {currentQuestion.title}
                      </h3>
                      <div className="space-y-3">
                        {currentQuestion.type === 'choice' && currentQuestion.options?.map((opt, idx) => (
                          <div key={idx} className="p-3 rounded-lg border border-slate-100 bg-slate-50 text-slate-600">
                            <span className="font-bold mr-2">{String.fromCharCode(65 + idx)}.</span>
                            {opt}
                          </div>
                        ))}
                        {currentQuestion.type === 'judge' && (
                          <>
                            <div className="p-3 rounded-lg border border-slate-100 bg-slate-50 text-slate-600">
                              <span className="font-bold mr-2">A.</span>
                              正确
                            </div>
                            <div className="p-3 rounded-lg border border-slate-100 bg-slate-50 text-slate-600">
                              <span className="font-bold mr-2">B.</span>
                              错误
                            </div>
                          </>
                        )}
                      </div>
                      <div className="mt-6 pt-6 border-t border-slate-50 flex justify-between items-center text-xs text-slate-400">
                        {/* <span>错误次数: {currentQuestion.errorCount}</span> */}
                        <span>添加时间: {new Date(currentQuestion.addedAt).toLocaleDateString()}</span>
                      </div>
                    </div>

                    {/* Back */}
                    <div className="absolute inset-0 [backface-visibility:hidden] [transform:rotateY(180deg)] bg-indigo-50 p-8 rounded-2xl shadow-sm border border-primary/20 flex flex-col overflow-y-auto">
                      <div className="flex items-center justify-between mb-6">
                        <span className="text-xs font-bold px-2 py-1 rounded bg-white text-primary uppercase tracking-wider shadow-sm">
                          Answer & Explanation
                        </span>
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleRemoveQuestion(currentQuestion.id);
                          }}
                          className="text-red-400 hover:text-red-600 p-1"
                          title="移除此题"
                        >
                          <Trash2 size={16} />
                        </button>
                      </div>
                      
                      <div className="mb-6">
                        <h4 className="text-sm font-bold text-slate-900 mb-2">正确答案</h4>
                        <div className="text-lg font-medium text-primary">
                          {Array.isArray(currentQuestion.correctAnswer)
                            ? currentQuestion.correctAnswer.join(', ')
                            : currentQuestion.correctAnswer}
                          {currentQuestion.type === 'judge' && (
                            <span className="text-sm text-slate-500 ml-2">
                              ({currentQuestion.correctAnswer === 'true' ? '正确' : '错误'})
                            </span>
                          )}
                        </div>
                      </div>

                      <div className="flex-1">
                        <h4 className="text-sm font-bold text-slate-900 mb-2">解析</h4>
                        <p className="text-slate-600 leading-relaxed">
                          {currentQuestion.explanation}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* Controls */}
              <div className="flex items-center justify-between mt-8 bg-white p-4 rounded-xl border border-slate-100 shadow-sm">
                <div className="flex items-center gap-2">
                  <button
                    onClick={handleRandomize}
                    className="flex items-center gap-2 px-4 py-2 rounded-lg hover:bg-slate-50 text-slate-600 hover:text-primary transition-colors text-sm font-medium"
                    title="随机抽取20题"
                  >
                    <Shuffle size={16} />
                    随机题目
                  </button>
                  {notebook.questions.length > 20 && (
                    <button
                      onClick={handleShowAll}
                      className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-colors text-sm font-medium ${
                        showAll
                          ? 'bg-indigo-50 text-primary'
                          : 'hover:bg-slate-50 text-slate-600 hover:text-primary'
                      }`}
                    >
                      <LayoutGrid size={16} />
                      全部试题 ({notebook.questions.length})
                    </button>
                  )}
                </div>

                <div className="flex items-center gap-4">
                  <button
                    disabled={activeQuestionIndex === 0}
                    onClick={() => {
                      setActiveQuestionIndex(prev => prev - 1);
                      setIsFlipped(false);
                    }}
                    className="p-2 rounded-full hover:bg-slate-100 text-slate-500 disabled:opacity-30 transition-colors"
                  >
                    <ChevronLeft size={24} />
                  </button>
                  <span className="text-sm font-medium text-slate-600 min-w-[3rem] text-center">
                    {activeQuestionIndex + 1} / {randomQuestions.length}
                  </span>
                  <button
                    disabled={activeQuestionIndex === randomQuestions.length - 1}
                    onClick={() => {
                      setActiveQuestionIndex(prev => prev + 1);
                      setIsFlipped(false);
                    }}
                    className="p-2 rounded-full hover:bg-slate-100 text-slate-500 disabled:opacity-30 transition-colors"
                  >
                    <ChevronRight size={24} />
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </Layout>
  );
};